import { type Config as SvgrOptions } from '@svgr/core';
import path from 'path';
import { fileURLToPath } from 'url';
import {
  transformSvgToComponent,
  type TransformSvgToComponentArgs,
} from './transform-svg';
import fs from 'fs';

import generator from '@babel/generator';

// 转换成 __filename 和 __dirname
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

/**
 * 自定义 输出 模板
 * @param variables
 * @param a
 * @returns
 */
const customTemplate: SvgrOptions['template'] = function (variables, a) {
  // 生成组件注释
  const svgAst = JSON.parse(JSON.stringify(variables.jsx));
  svgAst.openingElement.attributes.push(
    ...[
      {
        type: 'JSXAttribute',
        name: {
          type: 'JSXIdentifier',
          name: 'width',
        },
        value: {
          type: 'StringLiteral',
          value: '24',
        },
      },
      {
        type: 'JSXAttribute',
        name: {
          type: 'JSXIdentifier',
          name: 'height',
        },
        value: {
          type: 'StringLiteral',
          value: '24',
        },
      },
    ],
  );
  const svgCode = generator.default(svgAst).code;
  const base64 = Buffer.from(svgCode).toString('base64');
  const comment = `/**
  * ![${variables.componentName}](data:image/svg+xml;base64,${base64})
 */`;

  // 组件模版定义
  const statement = a.tpl`
  import * as React from 'react';
  import { wrapSvgComponent } from '../../components/icon-wrapper';
  type Props = React.SVGProps<SVGSVGElement>;


  const ${variables.componentName} = (props: Props) => (
    ${variables.jsx}
  );


  ${comment}
  const Icon = wrapSvgComponent(${variables.componentName});

  export default Icon;
  `;

  return statement;
};

/**
 * 把 icons/src/svgs 下所有的 svg 文件转换为 react 组件
 */
export async function buildIconComponent({
  entryDir,
  outputDir,
  prefix,
  suffix,
}: {
  entryDir: string;
  outputDir: string;
  prefix?: string;
  suffix?: string;
}) {
  const svgProps = {
    focusable: '{false}',
    role: 'img',
    'aria-hidden': '{true}',
    fill: 'currentColor',
  };

  const args: TransformSvgToComponentArgs = {
    entryDir,
    outputDir,
    svgProps,
    svgrOptions: {
      icon: true, // width="1em"
      typescript: true,
      prettier: true,
      svgo: true,
      jsxRuntime: 'classic',
      template: customTemplate,
      // 对svg进行优化处理
      svgoConfig: {
        // https://svgo.dev/docs/plugins/
        plugins: [
          'removeDesc', // 删除描述
          'removeTitle', // 删除标题
          'cleanupListOfValues', // 清理列表中的值
          'removeStyleElement', // 删除 style 元素
          'removeDimensions', // 删除 dimensions 属性
          'removeUnknownsAndDefaults', // 移除未知元素和属性，以及设置为默认值的属性
          {
            name: 'convertColors',
            params: {
              // 继承 css 中的 color; fill="currentColor"
              currentColor: true,
            },
          },
          {
            name: 'convertPathData',
            params: {
              // 浮点数精度
              floatPrecision: 2,
            },
          },
        ],
      },
    },
    prefix,
    suffix,
  };

  await transformSvgToComponent(args);
}

(() => {
  buildIconComponent({
    entryDir: path.resolve(__dirname, '../src/svgs/filled'),
    outputDir: path.resolve(__dirname, '../src/icons/filled'),
    suffix: 'filled',
  });

  buildIconComponent({
    entryDir: path.resolve(__dirname, '../src/svgs/outlined'),
    outputDir: path.resolve(__dirname, '../src/icons/outlined'),
    suffix: 'outlined',
  });

  fs.writeFileSync(
    path.resolve(__dirname, '../src/icons/index.ts'),
    `export * from './filled';\nexport * from './outlined';`,
    'utf-8',
  );
})();
